package com.nettyRpc.provider;

import com.nettyRpc.api.DubboRequest;
import org.reflections.Reflections;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Set;

/**
 *  反射读取
 */
public class InvokeSupport {
    public Object invoke(DubboRequest request) {
        try {
            // DubboRequest(id=100, className=com.nettyRpc.api.IHelloService, method=hello, args=[Hello World])

            Class clazz = Class.forName(request.getClassName());
            Object object = null;
            if (clazz.isInterface()) {

                object = getObject(clazz);
            }
            Class[] args = getArgs(request.getArgs());
            Method method = clazz.getMethod(request.getMethod(), args);
            // com.nettyRpc.provider.HelloServiceImpl——> 反射实现
            return method.invoke(object, request.getArgs());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Class[] getArgs(Object[] parameters) {
        int length = parameters == null ? 0 : parameters.length;
        Class[] args = new Class[length];
        for (int i = 0; i < length; i++) {
            args[i] = parameters[i].getClass();
        }
        return args;
    }

    /**
     * 根据接口获取实现类
     * 这边简单处理，只扫描指定路径下面的
     *
     * @param interfaceCLass
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    private Object getObject(Class interfaceCLass) throws IllegalAccessException, InstantiationException {
        interfaceCLass.getComponentType();
        interfaceCLass.getClass();
        interfaceCLass.getGenericSuperclass();
        Reflections reflections = new Reflections("com.nettyRpc");
        Set<Class> subTypes = reflections.getSubTypesOf(interfaceCLass);
        Iterator<Class> iterator = subTypes.iterator();
        while (iterator.hasNext()) {
            return iterator.next().newInstance();
        }
        return null;
    }
}
